package com.abe.libfitness.utils;

import androidx.annotation.IntDef;

import com.abe.libcore.utils.DailyLogUtils;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Date;

public class ProtocolV1Utils {
    public static final int SerialPortDefault = 100;//1000ms

    public static final byte empty = 0x00;
    public static final byte motorAddress = 0x01;//地址
    public static final byte typeRead = 0x03;//读命令
    public static final byte typeWrite = 0x06;//写命令

    public static final byte[] storageAddressMotor = {0x40, 0x01};//电机操作
    public static final byte[] storageAddressMotorStatus = {empty, 0x01};//读电机状态
    public static final byte[] storageAddressPower = {0x40, 0x02};//读写力量
    public static final byte[] storageAddressDistance = {empty, 0x02};//读距离
    //电机状态
    public static final int USR_IDLE = 0;
    public static final int USR_INIT = 1;
    public static final int USR_START = 2;
    public static final int USR_FIND_ZERO = 3;
    public static final int USR_RUN = 4;
    public static final int USR_STOP = 5;
    public static final int USR_WAIT = 6;
    public static final int USR_FAULT = 7;

    //电机启动或者停止
    public static byte[] motorAction(boolean start) {
        byte action;
        if (start) {
            action = 0x01;
        } else {
            action = 0x00;
        }
        byte[] command = {motorAddress, typeWrite, 0x40, 0x01, empty, action, empty, empty};
        return CRCChecker.getSendBuf(command);
    }

    //读电机状态
    public static byte[] motorStatus() {
        return CRCChecker.getSendBuf(new byte[]{motorAddress, typeRead, empty, 0x01, empty, 0x01, empty, empty});
    }

    //读力量
    public static byte[] readPower() {
        return CRCChecker.getSendBuf(new byte[]{motorAddress, typeRead, 0x40, 0x02, empty, 0x01, empty, empty});
    }

    //number :0-150
    public static byte[] writePower(int number) {
        if (number > 150) number = 150;
        if (number < 0) number = 0;
        return CRCChecker.getSendBuf(new byte[]{motorAddress, typeWrite, 0x40, 0x02, empty, intToByte(number), empty, empty});
    }

    public static byte[] readDistance() {
        return CRCChecker.getSendBuf(new byte[]{motorAddress, typeRead, empty, 0x02, empty, 0x01, empty, empty});
    }

    public static void saveLocalDailyLog(String message) {
        DailyLogUtils.INSTANCE.saveLocalDailyLog(new Date(), message, ConstantFitness.LOG_SERIAL_PATH);
    }

    //byte 与 int 的相互转换
    public static byte intToByte(int x) {
        return (byte) x;
    }

    public static int byte2Int(byte b) {
        return (int) (b & 0xff);
    }

    @IntDef({USR_IDLE, USR_INIT, USR_START, USR_FIND_ZERO, USR_RUN, USR_STOP, USR_WAIT, USR_FAULT})
    @Retention(RetentionPolicy.SOURCE)
    public @interface MotorStatus {

    }
}